"""
该脚本用来解析输入的内容
"""
import re

class RE(object):
    
    def __init__(self) -> None:
        super().__init__()
        # 先将固定的一些语法替换掉，避免复杂度
        self.CONST_MAP = {'{.}':'D','{..}':'DD','{...}':'DDD',
                        '{_}':'L','{__}':'LL','{___}':'LLL'}
        self.CONST_MAP1 = {'^...':'GGG','{___}':'LLL'}         

        self.CONST_MAP2 = {'^..':'GG','{__}':'LL'}
        self.CONST_MAP3 = {'^.':'G','{_}':'L'}

    def getSections(self,line):
        """
        拆分section，划分每个节
        """
        sections = [ i for i in line.split('|') if i not in [' ','']]
        return sections

    def getElements(self,section):
        """
        将每个section中的内容通过空格拆分
        """
        elements = [i for i in section.split(' ') if i not in [' ','']]
        return elements


    def isPair(self,string,char1,char2):
        """
        string : 输入的字符串
        char1: 成对出现的 右边括号
        char2: 成对出现的 左边括号
        """
        count_char1 = string.count(char1)
        count_char2 = string.count(char2)
        if count_char1 == count_char2:
            return True
        else:
            return False

    

    def get_all_indexs(self,string,pattern):
        indexs = []
        for i in range(len(string)):
            if string[i] == pattern:
                indexs.append(i)

        return indexs 


    def getInnerBraceContent(self,string):
        """
        匹配大括号获取最里层括号的内容，之后可以使用递归方式替换内容
        要匹配左边括号最近


        匹配规则，从最里面匹配开始。用最大索引的左括号与最小索引的右括号进行匹配
        '..{} .. {} ..{ ..{ ..{}..  }..  } '

        """
        if self.isPair(string,"{","}"):
            left_indexs = self.get_all_indexs(string,"{")
            right_indexs = self.get_all_indexs(string,"}")
            print("left_indexs:",left_indexs)
            print("right_indexs:",right_indexs)
            start_index = left_indexs[-1]
            end_index = right_indexs[0]
            if start_index<end_index:
                return string[start_index+1:end_index]
            else:
                return string

    def convertElement(self,element):
        for k,v in self.CONST_MAP.items():
            element = element.replace(k,v)

        return element



    def getReg(self, count, bracket = '{}'):
        leftBracket = bracket[0]
        rightBracket = bracket[1]
        count -= 1
        regBasic = leftBracket + '(?:[^' + leftBracket + rightBracket + '])*' + rightBracket
        if count < 0:
            regBasic = ''
        if count > 0:
            for i in range(count):
                tempNum = regBasic.rfind('*') - 1
                regBasic = regBasic[:tempNum] + "|" + regBasic + regBasic[tempNum:]
        return regBasic




if __name__=="__main__":
    r = RE()
    b = '(12) 12_{_} (33) 2^{.}'
    b = '(12) 12_{_} (33) 2^{2^{.}}'
    b = '12_{_}'
    # b = '2^{2^{.}}'
    content = r.getInnerBraceContent(b)
    # s = r.getReg(0)
    # pattern=re.compile(s)
    # content=pattern.match(b)
    print(content)
                










